package org.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.entity.Books;
import org.service.BooksService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * (Books)表控制层
 *
 * @author makejava
 * @since 2021-10-13 08:41:09
 */
//增加了@RestController之后，默认会解析字符串，不会跳转
@RestController
@RequestMapping("books2")
public class BooksController2 {
    /**
     * 服务对象
     */
    @Resource
    private BooksService booksService;
    //方式一：直接使用SimpleDateFormat
    @RequestMapping(value = "getTime")
    public String getTime(){
        Date date = new Date();//获取当前时间日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }
    //方式二：使用ObjectMapper转换格式（使用SimpleDateFormat做为格式）
    @RequestMapping(value = "getTime2")
    public String getTime2() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        //不使用时间戳的方式
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        //自定义日期格式对象
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //指定日期格式
        mapper.setDateFormat(sdf);
        Date date = new Date();
        String str = mapper.writeValueAsString(date);
        return str;
    }

    /**
     * 通过主键查询单条数据
     *  如何访问这个控制器的方法调用：/books/selectOne?id=xxx`
     *  参数名字和url参数名字相同就可以
     * @param id 主键
     * @return 单条数据的json字符串
     */
    @GetMapping("selectOne")
    public Books selectOne(Integer id) {
        return this.booksService.queryById(id);
    }

}